﻿using Sasa.QualityTools.CodeAnalysis.Common;
using Sasa.QualityTools.CodeAnalysis.Core.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Sasa.QualityTools.CodeAnalysis.Core.Repositories
{
    public class RuleSetRepository
    {
        private string bundleRuleSetDirectory;

        private string customRuleSetDirectory;


        public RuleSetRepository(string bundleRuleSetDirectory, string customRuleSetDirectory)
        {
            this.bundleRuleSetDirectory = bundleRuleSetDirectory;
            this.customRuleSetDirectory = customRuleSetDirectory;
        }


        public RuleSet FindRuleSetById(string id)
        {
            foreach (var ruleSet in FindRuleSets())
            {
                if (ruleSet.Id == id)
                {
                    return ruleSet;
                }
            }

            return null;
        }

        public IEnumerable<RuleSet> FindRuleSets()
        {
            var ruleSets = new List<RuleSet>();
            ruleSets.AddRange(FindRuleSets(bundleRuleSetDirectory, true));
            ruleSets.AddRange(FindRuleSets(customRuleSetDirectory, false));
            return ruleSets;
        }

        internal IEnumerable<RuleSet> FindRuleSets(string directory, bool isBundled)
        {
            if (Directory.Exists(directory))
            {
                foreach (string path in Directory.GetFiles(directory, "*.ruleset"))
                {
                    var ruleSet = new RuleSet();
                    ruleSet.Name = GetRuleSetName(path);
                    ruleSet.Id = ((isBundled) ? "Bundled" : "Custom") + ";" + Path.GetFileName(path);
                    ruleSet.Path = path;
                    yield return ruleSet;
                }
            }
        }

        internal string GetRuleSetName(string path)
        {
            try
            {
                var document = new XmlDocument();
                document.Load(path);
                var element = document.SelectSingleNode("/RuleSet/@Name");
                return (element != null) ? element.Value : Path.GetFileNameWithoutExtension(path);
            }
            catch (Exception e)
            {
                Logger.Error(String.Format("Failed to get RuleSet name of '{0}'.", path), e);
                throw;
            }
        }
    }
}
